package com.android.delivery.activity.fragment

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.android.delivery.App
import com.android.delivery.R
import com.android.delivery.activity.LanJianZhongXinActivity
import com.android.delivery.activity.OrderSettleActivity
import com.android.delivery.activity.PeiSongZhongXinActivity
import com.android.delivery.activity.siji.CaptureActivity
import com.android.delivery.activity.wangdian.CityAcceptFragment
import com.android.delivery.activity.wangdian.RiderHistoryOrderActivity
import com.android.delivery.adapter.BaseFragmentStateAdapter
import com.android.delivery.api.ApiService
import com.android.delivery.base.LazyFragment
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.entity.NetHome
import com.android.delivery.entity.even.RefreshUserEvent
import com.android.delivery.util.DensityUtil
import com.android.delivery.util.GlideUtil
import com.android.delivery.util.StringUtils
import com.android.delivery.util.print.ListUtils
import com.google.android.material.appbar.AppBarLayout
import com.lzy.okgo.model.Response
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.tbruyelle.rxpermissions3.RxPermissions
import com.wuhenzhizao.sku.utils.ScreenUtils
import kotlinx.android.synthetic.main.fragment_qishou.*
import kotlinx.android.synthetic.main.fragment_qishou.appBar
import kotlinx.android.synthetic.main.fragment_qishou.iv_photo
import kotlinx.android.synthetic.main.fragment_qishou.iv_photo_toolbar
import kotlinx.android.synthetic.main.fragment_qishou.layout_info
import kotlinx.android.synthetic.main.fragment_qishou.refreshLayout
import kotlinx.android.synthetic.main.fragment_qishou.refreshLayout_header
import kotlinx.android.synthetic.main.fragment_qishou.toolbar
import kotlinx.android.synthetic.main.fragment_qishou.tv_name
import kotlinx.android.synthetic.main.fragment_qishou.tv_name_toolbar
import kotlinx.android.synthetic.main.fragment_qishou.tv_phone
import kotlinx.android.synthetic.main.fragment_qishou.tv_phone_toolbar
import kotlinx.android.synthetic.main.fragment_qishou.tv_today_num
import kotlinx.android.synthetic.main.fragment_qishou.tv_week_num
import kotlinx.android.synthetic.main.fragment_qishou.view_pager
import kotlinx.android.synthetic.main.fragment_siji.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class QiShouFragment : LazyFragment() {

    private val mTitles: MutableList<String> = ArrayList()
    private val tabFragmentList: MutableList<Fragment> = ArrayList()

    override fun initViews(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater!!.inflate(R.layout.fragment_qishou, container, false)
    }

    override fun initData() {
    }

    override fun lazyInit() {
        val statusBarHeight = ScreenUtils.getStatusBarHeight(activity)
        layout_info.setPadding(0, statusBarHeight, 0, 0)

        mTitles.add("待接单")
        mTitles.add("同城已接单")
        tabFragmentList.add(QiShouDaiJieDanListFragment.newInstance())
        tabFragmentList.add(CityAcceptFragment.newInstance())
        view_pager.setAdapter(BaseFragmentStateAdapter(fragmentManager, tabFragmentList, mTitles))
        tab_layout.setupWithViewPager(view_pager)

        refreshLayout_header.setColorSchemeColors(resources.getColor(R.color.colorAccent))
        refreshLayout.setEnableLoadMore(false)
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                getHomeData()

                onRefreshFragment()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }

        })

        tv_ljzx.setOnClickListener {
            val intent = Intent(context, LanJianZhongXinActivity::class.java)
            startActivity(intent)
        }

        tv_pszx.setOnClickListener {
            val intent = Intent(context, PeiSongZhongXinActivity::class.java)
            startActivity(intent)
        }

        tv_spjj.setOnClickListener {
            var intent = Intent(context, OrderSettleActivity::class.java)
            startActivity(intent)
        }

        tv_ldjj.setOnClickListener {
            var intent = Intent(context, OrderSettleActivity::class.java)
            intent.putExtra(Constants.TYPE, OrderSettleActivity.TYPE_LINDAN_SEND)
            startActivity(intent)
        }

        iv_scan.setOnClickListener {
            RxPermissions(this).request(Manifest.permission.CAMERA).subscribe { aBoolean ->
                if (aBoolean) {
                    val intent = Intent(activity, CaptureActivity::class.java)
                    intent.putExtra(Constants.TYPE, CaptureActivity.TYPE_SCAN_DISPATCH)
                    startActivity(intent)
                }
            }
        }

        iv_scan_toolbar.setOnClickListener {
            RxPermissions(this).request(Manifest.permission.CAMERA).subscribe { aBoolean ->
                if (aBoolean) {
                    val intent = Intent(activity, CaptureActivity::class.java)
                    intent.putExtra(Constants.TYPE, CaptureActivity.TYPE_SCAN_DISPATCH)
                    startActivity(intent)
                }
            }
        }

        history_order_tv.setOnClickListener {
            var intent = Intent(context, RiderHistoryOrderActivity::class.java)
            startActivity(intent)
        }

        toolbar.layoutParams.height = statusBarHeight + DensityUtil.dp2px(44f)
        toolbar.setPadding(0, statusBarHeight, 0, 0)
        appBar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
            override fun onOffsetChanged(appBarLayout: AppBarLayout?, offset: Int) {
                var alpha = offset / layout_info.height.toFloat()
                if (alpha > 1) {
                    alpha = 1.0f
                }
                toolbar.alpha = (Math.abs(alpha))

                if (offset >= 0) {
                    setEnableRefresh(true)
                } else {
                    setEnableRefresh(false)
                }
            }
        })

        initUserInfo()
        getHomeData()
    }

    private fun onRefreshFragment() {
        if (!ListUtils.isEmpty(tabFragmentList)){
            val fragment = tabFragmentList.get(view_pager.currentItem)
            if (fragment != null){
                if (fragment is QiShouDaiJieDanListFragment) {
                    (fragment as QiShouDaiJieDanListFragment).onAutoRefresh()
                }else if (fragment is CityAcceptFragment) {
                    (fragment as CityAcceptFragment).onAutoRefresh()
                }
            }
        }
    }

    private fun getHomeData() {
        ApiService.getQishouHome(this, object : DialogCallback<LzyResponse<NetHome>>() {
            override fun onSuccess(response: Response<LzyResponse<NetHome>>) {
                refreshLayout.finishRefresh()
                val netHome = response.body().data
                if (netHome != null) {
                    tv_dlj.setText(netHome.waitPickQuantity.toString())
                    tv_ylj.setText(netHome.pickQuantity.toString())
                    tv_jrdd.setText(netHome.todayQuantity.toString())
                    tv_bzlj.setText(netHome.weekPickQuantity.toString())
                    tv_today_num.setText(netHome.weekDeliveryQuantity.toString())
                    tv_week_num.setText(netHome.waitPayQuantity.toString())
                }

            }

            override fun onError(response: Response<LzyResponse<NetHome>>?) {
                super.onError(response)
                refreshLayout.finishRefresh()
            }
        })
    }

    private fun initUserInfo() {
        val loginInfo = App.getInstance()?.getLoginInfo()
        if (loginInfo != null) {
            GlideUtil.loadCircleImg(iv_photo, loginInfo.user?.avatar)
            tv_name.setText(loginInfo.user?.nickname)
            tv_phone.setText(StringUtils.getFormatPhone(loginInfo.user?.mobile))

            GlideUtil.loadCircleImg(iv_photo_toolbar, loginInfo.user?.avatar)
            tv_name_toolbar.setText(loginInfo.user?.nickname)
            tv_phone_toolbar.setText(StringUtils.getFormatPhone(loginInfo.user?.mobile))
        }
    }

    private fun setEnableRefresh(enableRefresh: Boolean) {
        for (fragment in tabFragmentList) {
            if (fragment is QiShouDaiJieDanListFragment) {
                (fragment as QiShouDaiJieDanListFragment).setEnableRefresh(enableRefresh)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: RefreshUserEvent) {
        initUserInfo()
    }

    override fun isBindEventBus(): Boolean {
        return true
    }
}